<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2008 Starbugs <univis2typo3@googlegroups.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

require_once(PATH_tslib.'class.tslib_pibase.php');


/**
 * Plugin 'lectures' for the 'univis2typo3' extension.
 *
 * @author	Starbugs <univis2typo3@googlegroups.com>
 * @package	TYPO3
 * @subpackage	tx_univis2typo3
 */
class tx_univis2typo3_pi4 extends tslib_pibase {
	var $prefixId      = 'tx_univis2typo3_pi4';		// Same as class name
	var $scriptRelPath = 'pi4/class.tx_univis2typo3_pi4.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'univis2typo3';	// The extension key.
	var $pi_checkCHash = true;

	var $template = "";

	var $semester   = "";
	var $department = "";
	var $active = false;

	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content,$conf) {
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();
		$templateCode = $this->cObj->fileResource($this->conf['templateFile']);
		$this->template = $this->cObj->getSubpart($templateCode,"###TEMPLATE_LECTURES_PAGE###");

		$this->department = $this->conf['department_id'];
		$sem = $this->getRunningSemester();
		$this->semester   = $sem['year'].$sem['sem'];

		// Flex-Form initialisieren
		$this->pi_initPIflexForm();

// 		$this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display2', 'sDEF')
		$richt = t3lib_div::_GP('richt');
		$content  = $this->getContent();
		return $this->pi_wrapInBaseClass($content);
	}

	// getRunningSemester returns the running semester.
	function getRunningSemester() {
	    $m = (int) date('m');
	    $y = date('Y');
	    $term = 's';

	    if ($m <= 3) {
		// January till March -> still winter term of the previous year
		--$y;
		$term = 'w';
	    } else if ($m >= 10) {
		// September till December -> winter term of the current year
		$term = 'w';
	    }
	    // else -> summer term of the current year

	    // Do NOT update $this->year and $this->sem
	    // they store the current state of this object, not of reality
	    return array('year' => $y, 'sem' => $term);
	}

	function getNitems($lecturerKey = '', $maxNumber){
		return $this->getItems(null, $lecturerKey, $maxNumber);
	}
    
	function getItems($type = '', $lecturerKey = '', $maxNumber = 0)
	{
		if ($lecturerKey && !$this->semester) {
		    $sem = $this->getRunningSemester();
		    $this->semester = $sem['year'].$sem['sem'];
		}

		$select  = "*";
		$from	 = "`tx_u2t3_lecture` 
			JOIN `u_lecture_stud` ON `tx_u2t3_lecture`.`key` =`u_lecture_stud`.`lecture_key`";
		if ('' != $lecturerKey) {
		    $from .= " JOIN `u_lecture_dozs` ON `tx_u2t3_lecture`.`key` = `u_lecture_dozs`.`lecture_key`";
		}
		$where	 = "`tx_u2t3_lecture`.`semester` = '{$this->semester}' and `u_lecture_stud`.`semester` = '{$this->semester}' and `tx_u2t3_lecture`.`department_id` = {$this->department}";
		if ('' != $type) {
		    $where .= " AND `type` = '{$type}'";
		}
		if ('' != $lecturerKey) {
		    $where .= " AND `u_lecture_dozs`.`doz` = '{$lecturerKey}'";
		}
		$groupby = '`name`';
		$orderby = '`name`';
		$limit 	 = '';
		if ($maxNumber > 0) {
		    $limit = $maxNumber;
		}

		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,   	// SELECT
			$from,		// FROM
			$where,		// WHERE
			$groupby,	// GROUP BY
			$orderby,	// ORDER BY
			$limit		// LIMIT
		);
		
				return $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	}
// add parameters to function, like max items and lecturerkey and semester and type
	function getContent($lecturerKey = '', $maxNumber = 0, $allSemesters = false)
	{	
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			"*",																							// SELECT
			"`tx_u2t3_lecture` JOIN tx_u2t3_lecture_type_order ON `tx_u2t3_lecture`.type = `tx_u2t3_lecture_type_order`.type",	// FROM
			"department_id='".$this->department."' AND `semester`='".$this->semester."'",					// WHERE
			"`tx_u2t3_lecture`.type",																			// GROUP BY
			"sorting",																						// ORDER BY
			""											     												// LIMIT
		);

		$types = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		$result = '';
		while ( $typ = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($types) )
		{
			$items             = $this->getItems($typ['type'], $lecturerKey, $maxNumber );
			$arrMarker 	   	   = array();
			$arrWrappedSubpart = array();
			if(!($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items)))
				continue; // if query does not contain any items -> neXt

			$GLOBALS['TYPO3_DB']->sql_data_seek($items, 0); // reset internal pointer ==> only peek
			if(!$this->active) 
			{
				$arrWrappedSubpart['###TEMPLATE_THESIS_STATUS_CLASS###'] = "-active";
				$this->active = true;
			} else {
				$arrWrappedSubpart['###TEMPLATE_THESIS_STATUS_CLASS###'] = "";
			}
			
			
			if(0 == $GLOBALS["TSFE"]->sys_language_uid)
			{
				if($GLOBALS['TYPO3_DB']->sql_num_rows($items) == 1)
					$arrWrappedSubpart['###L_DESC###'] = $typ['description_en'];
				else
					$arrWrappedSubpart['###L_DESC###'] = $typ['description_en_plural'];
			} else {
				if($GLOBALS['TYPO3_DB']->sql_num_rows($items) == 1)
					$arrWrappedSubpart['###L_DESC###'] = $typ['description'];
				else
					$arrWrappedSubpart['###L_DESC###'] = $typ['description_plural'];
			}
			
			$content = '';
			while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items)) 
			{
				$arrMarker['###L_NAME###'] = $row['name'];
				$arrMarker['###L_URL###'] = $row['url_description'];

				// HH: moved HTML code into the template, where it belongs 
				$content .= $this->cObj->substituteMarkerArrayCached(
				    $this->cObj->getSubpart($this->template,"###TEMPLATE_LECTURE_ITEM###"),
				    $arrMarker);
			}
			
			$arrWrappedSubpart['###TEMPLATE_LECTURE_ITEM###'] = $content;
			$result .= $this->cObj->substituteMarkerArrayCached(
						$this->cObj->getSubpart($this->template,"###TEMPLATE_LECTURE_GROUP###"),
						$arrMarker,
						$arrWrappedSubpart);
		}
		
		$arrWrappedSubpart['###TEMPLATE_LECTURE_GROUP###'] = $result;

		// if no courses were found, return empty string instead of empty <div>
		if (!$result) return '';

		$arrMarker['###SLIDER_ID###'] = 'sldr-'.$this->semester;

		return  $this->cObj->substituteMarkerArrayCached(
						$this->template,
						$arrMarker,
						$arrWrappedSubpart);
	}

}
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi4/class.tx_univis2typo3_pi4.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi4/class.tx_univis2typo3_pi4.php']);
}

?>
